package com.aggregate.pay.xinfu.payment.support.client;

import javax.servlet.http.HttpServletRequest;

import com.aggregate.pay.xinfu.payment.bean.PayNotifyData;
import com.aggregate.pay.xinfu.payment.support.Client;
import com.aggregate.pay.xinfu.payment.support.Merch;
import com.aggregate.pay.xinfu.payment.support.utils.JSON;
import com.aggregate.pay.xinfu.payment.support.utils.MD5;

/**
 * 交易查询接口
 * @author Moyq5
 * @date 2018年8月31日
 */
public class PayNotify implements Client<HttpServletRequest, PayNotifyData> {
	private Merch merch;
	
	public PayNotify(Merch merch) {
		this.merch = merch;
	}

	@Override
	public PayNotifyData execute(HttpServletRequest req) {
		log.debug("信付代付回调 -> 请求地址：{}", req.getRequestURI());
		log.debug("信付代付回调 -> 请求参数：{}", req.getQueryString());
		PayNotifyData data = new PayNotifyData();
		try {
			
			String reqJson = req.getParameter("req");
			String reqSign = req.getParameter("sign");
			
			String signSrc = reqJson + merch.key();
			log.debug("信付代付回调 -> 签名内容：{}", signSrc);
			
			String sign = MD5.MD5Encode(signSrc).toLowerCase();
			log.debug("信付代付回调 -> 签名结果：{}", sign);
			
			if (!sign.equals(reqSign)) {
				throw new Exception("信付代付回调 -> 签名验证失败");
			}
			
			data = JSON.toObject(reqJson, PayNotifyData.class);
			
		} catch (Exception e) {
			log.error("信付代付回调 -> 处理失败", e);
			throw new RuntimeException(e);
		}
		return data;
	}

}
